import AdsIdConfig from "./AdsIdConfig";

export default class AdMGBackend {

    private static instance: AdMGBackend;
    public static getInstance(): AdMGBackend {
        if (!this.instance) {
            this.instance = new AdMGBackend();
        }
        return this.instance;
    }

    constructor() {
    }

    private url = 'https://backend.efunent.com/index.php/';
    private localData: LocalData = new LocalData();
    private platform = 0;
    private ad_block_cd = 0;

    /**
     * 请求后台，进行数据初始化，flyio跨平台请求
     * @param {*} platId 平台名 
     * @param {*} plat  平台命名空间
     * @param {*} pldId  媒体数据
     */
    ctrlData = {

    };

    async init(platform) {
        this.platform = platform;
        this.initPldData();
        await this.getDevId();
        await this.adIdInit();
        this.initPldAdData();
        console.log('AdMGBackend init');

        setInterval(() => {
            this.ad_block_cd += 0.1;
        }, 100);
    }

    /**获得用户id */
    async getDevId() {
        let _this = this;
        let devId = this.localData.devId;
        if (!devId) {
            let url: string;
            // url =this.url  + 'getUniqueDevid?model=' + (this.pldMG.backendData.systemInfo.model || 'test')
            url = this.url + 'getUniqueDevid?model=' + 'test';
            console.log("getUniqueDevid", url)

            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = xhr.responseText;
                    if (!data) {
                        console.log("初始化失败");
                        return;
                    }
                    let _resData = JSON.parse(data);
                    if (_resData.code == 200) {
                        console.log('getUniqueDevid', _resData);
                        _this.localData.devId = _resData.data;
                        _this.setDataToLocal();
                        this.newlyAddActive();
                    }
                }
            }.bind(this);
            xhr.open("GET", url, false);
            xhr.send();
        } else {
            this.newlyAddActive();
        }
    };

    /**uv 活跃统计 */
    private newlyAddActive() {

        let _this = this
        let url: string = this.url + "getLySDK" + this.urlGetData({
            mediaid: AdsIdConfig[this.getOpenId()]['PLDid'],
            devid: this.localData.devId
        });
        console.log("活跃统计url==>", url)

        let xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var data = xhr.responseText;
                if (!data) {
                    console.log("初始化失败");
                    return;
                }
                let _resData = JSON.parse(data);
                console.log('活跃统计上传成功', _resData);
            }
        }
        xhr.open("GET", url, true);
        xhr.send();
    };

    /**获取后台广告限制的配置 */
    adIdInit() {
        let openIdData = AdsIdConfig[this.getOpenId()];
        for (let k in openIdData) {
            let v = openIdData[k]
            if (!v)
                continue
            let url = this.url + 'getNewSwitch' + this.urlGetData({
                id: v,
                version: '2S'
            }); //广告数据包
            console.log("openID init", url);
            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var data = xhr.responseText;
                    if (!data) {
                        console.log("初始化失败");
                        return;
                    }
                    let _resData = JSON.parse(data);
                    if (_resData.code == 200) {
                        this.ctrlData[k] = _resData.data;
                    }
                }
            }.bind(this);
            xhr.open("GET", url, false);
            xhr.send();
        }
    };

    /**保存本地数据，用户唯一id，保存的时间 */
    private initPldData() {
        let data = this.getDataToLocal();
        if (data) {
            this.localData = data;
        } else {
            this.localData.devId = '';
            this.localData.lastLoginTime = 0;
            this.localData.ads = {};
        }
        this.setDataToLocal();
    }

    /**重置新的一天广告数据重置 */
    private initPldAdData() {

        let isnewday: boolean = false;
        let lgtime = new Date(this.localData.lastLoginTime);
        var lmouh = lgtime.getMonth();
        let lday = lgtime.getDate();
        let ngtime = new Date();
        var nmouh = ngtime.getMonth();
        let nday = ngtime.getDate();
        if (lmouh != nmouh) {
            isnewday = true;
        }
        if (nday != lday) {
            isnewday = true;
        }
        if (isnewday) {
            let _local = this.localData.ads;
            for (let k in AdsIdConfig[this.getOpenId()]) {
                _local[k] = {};
                _local[k].show = 0;
                _local[k].close = 0;
                _local[k].interval_now = 0
            }
        }
        this.localData.lastLoginTime = Date.now();
        this.setDataToLocal();
    }

    /**
     * 广告限制
     * ctrlKey: 对应OpenId里面的ctrlKey
     */
    public adShow(ctrlKey = undefined, show_complete = false) {
        if (!ctrlKey)
            return true;
        let _local = this.localData.ads[ctrlKey];
        if (!_local)
            return true;

        let _ctrl = this.ctrlData[ctrlKey];
        let rand = Math.random();
        if (!_ctrl ||
            _ctrl.is_free ||
            !_ctrl.ad_switch ||
            _ctrl.show_blank > 0 && _ctrl.show_blank > this.ad_block_cd ||
            _ctrl.show_limit > 0 && _local.show >= _ctrl.show_limit ||
            _ctrl.close_counts > 0 && _local.close >= _ctrl.close_counts ||
            _ctrl.show_rate && _ctrl.show_rate < rand ||
            _ctrl.interval > 0 && _local.interval_now > 0) {
            console.log('广告限制', ctrlKey,
                _ctrl, !_ctrl && 'ctrlId error' ||
                !_ctrl.ad_switch && 'ad_switch close' ||
                _ctrl.show_blank > 0 && _ctrl.show_blank > this.ad_block_cd && 'ad_block_cd' + _ctrl.show_blank + " " + this.ad_block_cd ||
                _ctrl.is_free && 'isFree' ||
                _ctrl.show_limit > 0 && _local.show >= _ctrl.show_limit && 'show_limit' ||
                _ctrl.close_counts > 0 && _local.close >= _ctrl.close_counts && 'close_counts' ||
                _ctrl.show_rate && _local.show_rate < rand && 'random' ||
            _ctrl.interval > 0 && _local.interval_now > 0 && 'interval')
            return false;
        }
        console.log(_local);
        if (show_complete) {
            _local.show++;
            _local.interval_now = _ctrl.interval;
            this.setDataToLocal();
            if (_ctrl.rate > Math.random()) {
                return false;
            }
        }
        return true;
    }

    adClose(ctrlKey: string | number) {
        if (!ctrlKey)
            return
        console.log(ctrlKey, this.localData.ads[ctrlKey]);
        this.localData.ads[ctrlKey].close++;
        this.setDataToLocal();
    }

    private getOpenId() {
        let openId = '';
        switch (this.platform) {
            case Platform.oppo_H5:
                openId = 'oppoOpenId'; break;
            case Platform.vivo_H5:
                openId = 'vivoOpenId'; break;
            case Platform.qq_H5:
                openId = 'qqOpenId'; break;
            case Platform.weixin_H5:
                openId = 'wxOpenId'; break;
            case Platform.meizu_H5:
                openId = 'meizuOpenId'; break;
            case Platform.toutiao_H5:
                openId = 'toutiaoOpenId'; break;
            case Platform.baidu_H5:
                openId = 'baiduOpenId'; break;
            case Platform.huawei_H5:
                openId = 'huaweiOpenId'; break;
        }
        return openId;
    }

    private getDataToLocal() {
        let objStr = cc.sys.localStorage.getItem("pldData");
        if (!objStr) {
            return null;
        }
        return JSON.parse(objStr);
    }

    private setDataToLocal() {
        console.log('pldData == >', JSON.stringify(this.localData));
        cc.sys.localStorage.setItem("pldData", JSON.stringify(this.localData));
    }

    private urlGetData(obj) {
        let str = ''
        for (let k in obj) {
            let isFirst = false;
            if (str == '')
                isFirst = true
            str += (!isFirst && '&' || '') + k + '=' + obj[k]
        }
        return '?' + str
    }
}

export enum Platform {
    oppo_H5 = 1,
    vivo_H5,
    qq_H5,
    weixin_H5,
    baidu_H5,
    toutiao_H5,
    meizu_H5,
    huawei_H5
}

class LocalData {
    devId: string;
    lastLoginTime: number;

    ads: any;
}
